<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { registerMerchant, getAllMerchantCategories } from '@/api/merchant'
import type { MerchantRegisterParams, MerchantCategory } from '@/api/merchant'

const router = useRouter()
const loading = ref(false)
const categories = ref<MerchantCategory[]>([])
const formRef = ref()

// 商家注册表单
const registerForm = reactive<MerchantRegisterParams>({
  username: '',
  password: '',
  name: '',
  address: '',
  phone: '',
  description: '',
  image: '',
  businessHours: '09:00-22:00',
  deliveryFee: 5,
  minOrderAmount: 20,
  categoryId: 0,
  status: 1  // 添加默认状态值为1（正常状态）
})

// 确认密码
const confirmPassword = ref('')
// 密码是否一致
const passwordsMatch = ref(true)

// 监听密码变化
watch([() => registerForm.password, confirmPassword], ([newPassword, newConfirmPassword]) => {
  if (newConfirmPassword && newPassword !== newConfirmPassword) {
    passwordsMatch.value = false
  } else {
    passwordsMatch.value = true
  }
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 3, message: '用户名长度不能小于3个字符' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码长度不能小于6个字符' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码' },
    { 
      validator: (value: string, cb: (error?: string) => void) => {
        if (value !== registerForm.password) {
          passwordsMatch.value = false
          cb('两次输入的密码不一致')
        } else {
          passwordsMatch.value = true
          cb()
        }
      }
    }
  ],
  name: [
    { required: true, message: '请输入商家名称' }
  ],
  address: [
    { required: true, message: '请输入商家地址' }
  ],
  phone: [
    { required: true, message: '请输入联系电话' },
    { 
      match: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号码' 
    }
  ],
  description: [
    { required: true, message: '请输入商家描述' }
  ],
  businessHours: [
    { required: true, message: '请输入营业时间' }
  ],
  deliveryFee: [
    { required: true, message: '请输入配送费' },
    { 
      validator: (value: number, cb: (error?: string) => void) => {
        if (value < 0) {
          cb('配送费不能为负数')
        } else {
          cb()
        }
      }
    }
  ],
  minOrderAmount: [
    { required: true, message: '请输入起送金额' },
    { 
      validator: (value: number, cb: (error?: string) => void) => {
        if (value < 0) {
          cb('起送金额不能为负数')
        } else {
          cb()
        }
      }
    }
  ],
  categoryId: [
    { 
      validator: (value: number, cb: (error?: string) => void) => {
        if (value === 0) {
          cb('请选择商家分类')
        } else {
          cb()
        }
      }
    }
  ]
}

// 获取商家分类
const fetchCategories = async () => {
  try {
    const response = await getAllMerchantCategories()
    if (response.code === 200) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取商家分类失败:', error)
    Message.error('获取商家分类失败，请稍后再试')
  }
}

// 初始化获取商家分类
fetchCategories()

// 处理注册
const handleRegister = async () => {
  // 使用表单验证
  formRef.value.validate().then(async () => {
    // 再次检查密码是否一致
    if (registerForm.password !== confirmPassword.value) {
      Message.error('两次输入的密码不一致，请重新输入')
      return
    }

    loading.value = true
    try {
      const response = await registerMerchant(registerForm)
      
      if (response.code === 200) {
        Message.success('注册成功，请登录')
        router.push('/merchant/login')
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (error: any) {
      console.error('注册失败:', error)
      Message.error('注册失败: ' + (error.message || '请稍后再试'))
    } finally {
      loading.value = false
    }
  }).catch((errors: any) => {
    console.log('表单验证失败:', errors)
    Message.error('请检查表单填写是否正确')
  })
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/merchant/login')
}

// 返回首页
const goToHome = () => {
  router.push('/')
}
</script>

<template>
  <div class="merchant-register-container">
    <div class="register-header">
      <a-button shape="circle" @click="goToHome">
        <template #icon><icon-left /></template>
      </a-button>
      <h2>商家注册</h2>
      <div></div>
    </div>

    <div class="register-form">
      <a-form
        ref="formRef"
        :model="registerForm"
        :rules="rules"
        layout="vertical"
        @submit.prevent
      >
        <h3>账号信息</h3>
        <a-form-item field="username" label="用户名">
          <a-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            allow-clear
          >
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="password" label="密码">
              <a-input-password
                v-model="registerForm.password"
                placeholder="请输入密码"
                allow-clear
              >
                <template #prefix>
                  <icon-lock />
                </template>
              </a-input-password>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item field="confirmPassword" label="确认密码">
              <a-input-password
                v-model="confirmPassword"
                placeholder="请再次输入密码"
                allow-clear
              >
                <template #prefix>
                  <icon-check-circle />
                </template>
              </a-input-password>
            </a-form-item>
          </a-col>
        </a-row>

        <h3>商家信息</h3>
        <a-form-item field="name" label="商家名称">
          <a-input
            v-model="registerForm.name"
            placeholder="请输入商家名称"
            allow-clear
          >
            <template #prefix>
              <icon-shop />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item field="categoryId" label="商家分类">
          <a-select
            v-model="registerForm.categoryId"
            placeholder="请选择商家分类"
            allow-clear
          >
            <a-option
              v-for="category in categories"
              :key="category.id"
              :value="category.id"
              :label="category.name"
            />
          </a-select>
        </a-form-item>
        
        <a-form-item field="phone" label="联系电话">
          <a-input
            v-model="registerForm.phone"
            placeholder="请输入联系电话"
            allow-clear
          >
            <template #prefix>
              <icon-phone />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item field="address" label="商家地址">
          <a-input
            v-model="registerForm.address"
            placeholder="请输入商家地址"
            allow-clear
          >
            <template #prefix>
              <icon-location />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item field="description" label="商家描述">
          <a-textarea
            v-model="registerForm.description"
            placeholder="请输入商家描述"
            allow-clear
          />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="businessHours" label="营业时间">
              <a-input
                v-model="registerForm.businessHours"
                placeholder="如：09:00-22:00"
                allow-clear
              >
                <template #prefix>
                  <icon-clock-circle />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          
          <a-col :span="8">
            <a-form-item field="deliveryFee" label="配送费（元）">
              <a-input-number
                v-model="registerForm.deliveryFee"
                placeholder="配送费"
                :min="0"
                :step="1"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="8">
            <a-form-item field="minOrderAmount" label="起送金额（元）">
              <a-input-number
                v-model="registerForm.minOrderAmount"
                placeholder="起送金额"
                :min="0"
                :step="5"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item field="image" label="商家图片">
          <a-input
            v-model="registerForm.image"
            placeholder="请输入商家图片URL"
            allow-clear
          >
            <template #prefix>
              <icon-image />
            </template>
          </a-input>
        </a-form-item>
        
        <div class="form-actions">
          <a-button type="text" @click="goToLogin">已有账号？去登录</a-button>
        </div>
        
        <a-button
          type="primary"
          long
          size="large"
          :loading="loading"
          @click="handleRegister"
        >
          注册
        </a-button>
      </a-form>
    </div>
  </div>
</template>

<style scoped>
.merchant-register-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.register-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
}

.register-header h2 {
  margin: 0;
  font-size: 24px;
  color: var(--color-text-1);
}

.register-form {
  background-color: var(--color-bg-2);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.register-form h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: var(--color-text-1);
  padding-bottom: 8px;
  border-bottom: 1px solid var(--color-border);
}

.register-form h3:not(:first-child) {
  margin-top: 24px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .merchant-register-container {
    padding: 16px;
  }
  
  .register-form {
    padding: 16px;
  }
}

/* 表单样式优化 */
:deep(.arco-form-item) {
  margin-bottom: 20px;
}

:deep(.arco-input),
:deep(.arco-input-password),
:deep(.arco-textarea),
:deep(.arco-select) {
  border-radius: 6px;
}

/* 按钮样式优化 */
:deep(.arco-btn) {
  border-radius: 6px;
  height: 40px;
  font-weight: 500;
}
</style> 